#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QPixmap>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QBuffer>
#include <QFile>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished,
            this, &Widget::handle_reply);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_openButton_clicked()
{
    QString filename = QFileDialog::getOpenFileName();
    QPixmap image(filename);
    ui->sourceLabel->setPixmap(image.scaled(ui->sourceLabel->size(), Qt::KeepAspectRatio));
}


void Widget::on_saveButton_clicked()
{
    QString filename = QFileDialog::getSaveFileName();
    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    ui->resultLabel->pixmap()->save(&file, "JPG");
    file.close();
}

void Widget::on_changeButton_clicked()
{
    if (ui->tokenEdit->text().isEmpty())
    {
        QMessageBox::warning(this, "错误", "Token为空");
        return;
    }

    QUrl url("https://aip.baidubce.com/rest/2.0/face/v1/editattr");
    QUrlQuery query;
    query.addQueryItem("access_token", ui->tokenEdit->text());
    url.setQuery(query);

    qDebug() << url.toString();

    QNetworkRequest request(url);
    request.setRawHeader("Content-Type", "application/json");

    QBuffer buf;
    buf.open(QIODevice::WriteOnly);
    ui->sourceLabel->pixmap()->save(&buf, "JPG");
    QByteArray base64 = buf.data().toBase64();
    buf.close();

    QJsonObject root;
    root["image"] = QString(base64);
    root["image_type"] = "BASE64";
    root["action_type"] = "V2_AGE"; //年龄
    root["target"] = ui->ageSlider->value(); //1~85岁

    client->post(request, QJsonDocument(root).toJson());
}

void Widget::handle_reply(QNetworkReply* reply)
{
    QJsonDocument json = QJsonDocument::fromJson(reply->readAll());
    reply->deleteLater();
    if (json["error_code"].toInt() != 0)
    {
        QMessageBox::warning(this, "错误", json["error_msg"].toString());
        return;
    }
    QString base64 = json["result"]["image"].toString();
    QPixmap image;
    image.loadFromData(QByteArray::fromBase64(base64.toUtf8()));
    ui->resultLabel->setPixmap(image);
}
